package com.hu.bgp.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.google.gwt.user.server.rpc.SerializationPolicy;
import com.google.gwt.user.server.rpc.SerializationPolicyLoader;

import com.hu.bgp.exceptions.BgpServerException;
import com.hu.bgp.framework.clientapi.BoardGameService;
import com.hu.bgp.framework.clientapi.ClientToServerMessage;
import com.hu.bgp.framework.clientapi.ServerToClientMessage;

import de.novanic.eventservice.service.RemoteEventServiceServlet;

/**
 * De 'main' servlet die binnenkomende berichten doorgeeft naar de juiste games
 * en de PlayerClient aanstuurt.
 * 
 * @author ejvos
 */
public class BoardGameServiceImpl extends RemoteEventServiceServlet implements
		BoardGameService
{
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		System.out.println("BoardGameServiceImpl.init");
		GameServerContext gsc = GameServerContext
				.getInstance(getServletContext());
	}

	public void handleMessage(ClientToServerMessage message) {
		System.out.println("BoardGameServiceImpl.handleMessage");
		GameServerContext gsc = GameServerContext
				.getInstance(getServletContext());

		gsc.dispatchMessageToGameInstance(message);
	}

	protected SerializationPolicy doGetSerializationPolicy(
			HttpServletRequest request, String moduleBaseURL, String strongName) {
		System.out.println("BoardGameServiceImpl.doGetSerializationPolicy");
		// The request can tell you the path of the web app relative to the
		// container root.
		String contextPath = request.getContextPath();

		String modulePath = null;
		if (moduleBaseURL != null) {
			try {
				modulePath = new URL(moduleBaseURL).getPath();
			} catch (MalformedURLException ex) {
				System.out.println(ex.toString());
			}
		}

		SerializationPolicy serializationPolicy = null;

		/*
		 * Check that the module path must be in the same web app as the servlet
		 * itself. If you need to implement a scheme different than this,
		 * override this method.
		 */
		if (modulePath == null || !modulePath.startsWith(contextPath)) {
			String message = "ERROR: The module path requested, "
					+ modulePath
					+ ", is not in the same web application as this servlet, "
					+ contextPath
					+ ".  Your module may not be properly configured or your client and server code maybe out of date.";
			System.out.println(message);
		} else {
			// Strip off the context path from the module base URL. It should be
			// a strict prefix.
			String contextRelativePath = modulePath.substring(contextPath
					.length());

			String serializationPolicyFilePath = SerializationPolicyLoader
					.getSerializationPolicyFileName(contextRelativePath
							+ strongName);

			// Open the RPC resource file and read its contents.
			GameServerContext gsc = GameServerContext
					.getInstance(getServletContext());
			File file = gsc
					.getResourcesFileByContextPath(serializationPolicyFilePath);
			InputStream is = null;
			try {
				is = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				// ignored, checks for null are performed
			}
			try {
				if (is != null) {
					try {
						serializationPolicy = SerializationPolicyLoader
								.loadFromStream(is, null);
					} catch (ParseException e) {
						System.out
								.println("ERROR: Failed to parse the policy file '"
										+ serializationPolicyFilePath + "'");
					} catch (IOException e) {
						System.out
								.println("ERROR: Could not read the policy file '"
										+ serializationPolicyFilePath + "'");
					}
				} else {
					String message = "ERROR: The serialization policy file '"
							+ serializationPolicyFilePath
							+ "' was not found; did you forget to include it in this deployment?";
					System.out.println(message);
				}
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						// Ignore this error
					}
				}
			}
		}

		return serializationPolicy;
	}

	// Dummy methods for GWT serialzation
	public ServerToClientMessage sendMessage_dummy() {
		throw new BgpServerException(
				"This method shall never be used! its purpse is only to mark the serialization classes");
	}

}
